from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import uvicorn
from loguru import logger
import os
from datetime import datetime

from app.api import conversation, processing, chart
from app.core.config import settings


@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时
    logger.info("Starting博沃智慧AI后端服务...")
    yield
    # 关闭时
    logger.info("Shutting down博沃智慧AI后端服务...")


app = FastAPI(
    title="博沃智慧AI API",
    description="博沃智慧AI后端API服务",
    version="1.0.0",
    lifespan=lifespan
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "http://localhost:3001"],  # 前端地址
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含路由
app.include_router(conversation.router, prefix="/api/conversations", tags=["对话"])
app.include_router(processing.router, prefix="/api/processing", tags=["处理"])
app.include_router(chart.router, prefix="/api/charts", tags=["图表"])


@app.get("/")
async def root():
    return {"message": "博沃智慧AI API服务运行中", "timestamp": datetime.now()}


@app.get("/health")
async def health_check():
    return {"status": "healthy", "timestamp": datetime.now()}


if __name__ == "__main__":
    # 确保数据目录存在
    os.makedirs("data", exist_ok=True)
    os.makedirs("logs", exist_ok=True)
    
    # 配置日志
    logger.add("logs/app.log", rotation="1 day", retention="7 days")
    
    # 启动服务器
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )